﻿/*
=======================================================
    HoisterUsage【提升用途】
=======================================================
*/

namespace Services
{
    public interface IHoisterUsageRepository : IRepository<HoisterUsage>
    {
        int UpdateIsDelete(bool flag, int[] ids);
    }


    public class HoisterUsageRepository : BaseRepository<HoisterUsage>, IHoisterUsageRepository
    {
        public HoisterUsageRepository(ISqlSugarClient dB, ICurrentUser currentUser, IQuery<HoisterUsage> query)
            : base(dB, currentUser, query)
        {
        }

        #region 启用/禁用  UpdateIsDelete
        public int UpdateIsDelete(bool flag, int[] ids)
        {
            return _DB.Updateable<HoisterUsage>()
                      .SetColumns(x => new HoisterUsage { IsDelete = flag })
                      .Where(x => ids.Contains(x.HoisterUsageID))
                      .ExecuteCommand();
        }
        #endregion

        #region GetPage
        public override (List<HoisterUsage> items, int totalCount) GetPage(Expressionable<HoisterUsage> where, int pageIndex = 1, int pageSize = 20, string orderBy = null)
        {
            var fs = _DB.Queryable<HoisterUsage, Hoister>
                ((x, h) => new JoinQueryInfos(
                    JoinType.Inner, x.HoisterID == h.HoisterID
                ))
                .Select((x, h) => new HoisterUsage
                {
                    HoisterUsageID = x.HoisterUsageID.SelectAll(),
                    Hoister_Name = h.Name,
                });

            return _query.GetPage(where, pageIndex, pageSize, orderBy, fs);
        }
        #endregion

        #region Insert
        public override int Insert(HoisterUsage entity)
        {
            var id = base.Insert(entity);

            //得到当前账户下所有的状态标准数据，对于现在来说，就是固定的4条
            var standStatuss = _DB.Queryable<StandStatus>().Where(x => x.GroupInfoID == _currentUser.CurrentUserInfo.LoginTypeID).ToList();

            //得到当前添加的提升用途时选择的提升机类型，在钢丝绳类型里数据
            var wireropeTypes = _DB.Queryable<WireropeType>().Where(x => x.HoisterID == entity.HoisterID).ToList();

            //得到状态标准明细的模板数据
            var standStatusDetails = wireropeTypes.Select(x => new StandStatusDetail
            {
                GroupInfoID = _currentUser.CurrentUserInfo.LoginTypeID,
                HoisterID = entity.HoisterID,
                HoisterUsageID = id,
                WireropeTypeID = x.WireropeTypeID,
            }).ToList();

            //循环状态标准，通过状态标准明细模板的集合，一次性添加N条对应状态标准的明细数据
            standStatuss.Each(x =>
            {
                standStatusDetails.Each(y =>
                {
                    y.StandStatusID = x.StandStatusID;
                });

                _DB.Insertable(standStatusDetails).ExecuteCommand();
            });

            return id;
        } 
        #endregion
    }
}
